package com.zk.iotgateway.controller;

import com.zk.iotgateway.domain.Msg;
import com.zk.iotgateway.domain.param.IotConfigDO;
import com.zk.iotgateway.domain.param.IotDispatchDO;
import com.zk.iotgateway.service.IotConfigService;
import com.zk.iotgateway.service.IotDispatchService;
import com.zk.iotgateway.util.ResultUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * ${DESCRIPTION}
 *
 * @author:mn.m
 * @create 2019-05-05 下午 04:29
 **/
@Controller
@RequestMapping("/iot/dispatch/")
public class IotDispatchController {

    private static final Logger log= LoggerFactory.getLogger(IotDispatchController.class);

    @Autowired
    private IotDispatchService iotDispatchService;
    @Autowired
    private IotConfigService iotConfigService;


    @GetMapping("listPage")
    @ResponseBody
    public Msg listPage(){
        try {
            List<Map<String, String>> dispatchList = iotDispatchService.findDispatchList();
            if (dispatchList!= null&&!dispatchList.isEmpty()){
                return ResultUtil.success(dispatchList);
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.failure();
        }
        return ResultUtil.success();
    }



    @GetMapping("list/{port}")
    @ResponseBody
    public Msg list(@PathVariable String port){
        try {
            List<IotDispatchDO> list=null;
            if (port!=null&&port.length()>0){
               list=iotDispatchService.findByCondition(port);
            }
            return ResultUtil.success(list);
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.failure();
        }
    }

    @GetMapping("addpage")
    public ModelAndView addIotServer(){
        ModelAndView view=new ModelAndView();
        List<IotConfigDO> configList =iotConfigService.findAll();
        view.addObject("configs",configList);
        view.setViewName("dispatch/dispatch_add");
        return view;
    }

    @RequestMapping("save")
    @ResponseBody
    public Msg saveConfig(IotDispatchDO iotDispatchDO){
        if (validForm(iotDispatchDO)){
            return ResultUtil.cutomfailure("表单数据不能为空！！");
        }
        iotDispatchDO.setId(UUID.randomUUID().toString());
        iotDispatchService.save(fulField(iotDispatchDO));
        if (iotDispatchDO!= null){
           if ("1".equals(iotDispatchDO.getIsOpen())){
               iotDispatchService.addMq(iotDispatchDO);
           }
        }
        return ResultUtil.customSuccess("添加成功");
    }

    @RequestMapping("removeBatch/{ids}")
    @ResponseBody
    public Msg removeBatch(@PathVariable String ids){
        if (ids!=null&&ids.length()>0){
            String[] idarr=ids.split(",");
            for (String item:idarr) {
                iotDispatchService.remove(item);
            }
            return ResultUtil.customSuccess("成功删除"+idarr.length+"行记录");
        }
        return ResultUtil.cutomfailure("参数不能为空!");
    }

    @RequestMapping("view/{id}")
    @ResponseBody
    public ModelAndView  view(@PathVariable String id){
        ModelAndView view=new ModelAndView();
        if (id!=null&&id.length()>0){
            List<IotConfigDO> configList =iotConfigService.findAll();
            view.addObject("configs",configList);
            IotDispatchDO iotDispatchDO=iotDispatchService.findById(id);
            view.addObject("iotdispatch",iotDispatchDO);
        }
        view.setViewName("dispatch/dispatch_add");
        return view;
    }

    @PostMapping("update")
    @ResponseBody
    public Msg edit(IotDispatchDO iotDispatchDO){
        if(iotDispatchDO==null){
            return ResultUtil.beanIsNull();
        }
        if (validForm(iotDispatchDO)){
            return ResultUtil.cutomfailure("表单信息不全，请填写完整！");
        }
        iotDispatchService.updateEntity(fulField(iotDispatchDO));
        iotDispatchService.removeMQ(iotDispatchDO);
        if ("1".equals(iotDispatchDO.getIsOpen())){
            iotDispatchService.addMq(iotDispatchDO);
        }
        return ResultUtil.success();
    }

    /*
     * 启用
     * */
    @GetMapping("start/{id}")
    @ResponseBody
    public Msg startPort(@PathVariable  String id){
        try{
            if (id!=null&&id.length()>0){
                IotDispatchDO byId = iotDispatchService.findById(id);
                byId.setIsOpen("1");
                iotDispatchService.updateEntity(byId);
                iotDispatchService.addMq(byId);
                return ResultUtil.customSuccess("启用成功！");
            }
            return ResultUtil.cutomfailure("参数不能为空!");
        }catch (Exception e){
            e.printStackTrace();
            return ResultUtil.cutomfailure("启用失败!");
        }
    }

    /*
     * 禁用
     * */
    @GetMapping("cancel/{id}")
    @ResponseBody
    public Msg cancel(@PathVariable  String id){
        try{
            if (id!=null&&id.length()>0){
                IotDispatchDO byId = iotDispatchService.findById(id);
                byId.setIsOpen("0");
                iotDispatchService.updateEntity(byId);
                iotDispatchService.removeMQ(byId);
                return ResultUtil.customSuccess("禁用成功！");
            }
            return ResultUtil.cutomfailure("参数不能为空!");
        }catch (Exception e){
            e.printStackTrace();
            return  ResultUtil.cutomfailure("禁用失败!");
        }
    }





    private boolean validForm(Object bean){
        if (bean instanceof IotDispatchDO){
            IotDispatchDO iotDispatchDO= (IotDispatchDO) bean;
            if (StringUtils.isEmpty(iotDispatchDO.getPort())){
                return true;
            }
            if (StringUtils.isEmpty(iotDispatchDO.getAddress())){
                return true;
            }
            if (StringUtils.isEmpty(iotDispatchDO.getQueueName())){
                return true;
            }
            if (StringUtils.isEmpty(iotDispatchDO.getUsername())){
                return true;
            }
            if (StringUtils.isEmpty(iotDispatchDO.getPassword())){
                return true;
            }
        }
        return false;
    }

    private IotDispatchDO fulField(IotDispatchDO iotDispatchDO){
        if (StringUtils.isEmpty(iotDispatchDO.getMqport())){
            iotDispatchDO.setMqport("5672");
        }
        if (StringUtils.isEmpty(iotDispatchDO.getPublisherConfirm())){
            iotDispatchDO.setPublisherConfirm("1");
        }
        if (StringUtils.isEmpty(iotDispatchDO.getVirtualHost())){
            iotDispatchDO.setVirtualHost("/");
        }
        if (StringUtils.isEmpty(iotDispatchDO.getExchangeType())){
            iotDispatchDO.setExchangeType(BuiltinExchangeType.DIRECT.getType());
        }
        if (StringUtils.isEmpty(iotDispatchDO.getRoutingKey())
                    &&!StringUtils.isEmpty(iotDispatchDO.getQueueName())){
            iotDispatchDO.setRoutingKey(iotDispatchDO.getQueueName());
        }
        return iotDispatchDO;
    }

}
